package com.czwx.bee.business.manager.modular.sys.service.impl;

import cn.hutool.core.util.StrUtil;
import com.czwx.bee.business.manager.modular.sys.mapper.RoleDao;
import com.czwx.bee.business.manager.modular.sys.model.Resource;
import com.czwx.bee.business.manager.modular.sys.model.Role;
import com.czwx.bee.business.manager.modular.sys.model.SecurityUser;
import com.czwx.bee.business.manager.modular.sys.service.RoleService;
import com.czwx.bee.business.manager.utils.SecurityUtil;
import org.beetl.sql.core.Params;
import org.beetl.sql.core.SQLManager;
import org.beetl.sql.core.engine.PageQuery;
import org.beetl.sql.core.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private SQLManager sqlManager;

    @Override
    public List<Map> findUserRoleByUid(Long uid) {
        String sql="select a.name,a.id from bp_role a join bp_user_role b on a.id=b.role_id where b.user_id=#uid#";

        return sqlManager.execute(sql,Map.class, Params.ins().add("uid", uid).map());
    }

    @Override
    @Transactional
    public Boolean AuthRoleResource(Long rid,String[]ids) {

         String sql="delete from bp_role_resource where role_id=#rid#";
         sqlManager.executeUpdate(sql,Params.ins().add("rid",rid).map());
         System.out.print(ids.length);
         if(ids.length>1){
             sql="INSERT INTO bp_role_resource (role_id,resource_id) VALUES ";
             for(int i=0;i<ids.length;i++){
                 sql+="("+rid+","+ids[i]+")";
                 if(i!=ids.length-1){
                     sql+=",";
                 }
             }
             if(sqlManager.executeUpdate(sql,null)==0){
                 return  false;
             }
         }
        return true;
    }

    @Override
    public List<Map> roleResources(Long rid) {
        String sql="select DISTINCT(c.id),c.pid,c.name from bp_role a join bp_role_resource b on a.id=b.role_id join bp_resource c on b.resource_id=c.id where a.id=#rid# order by a.seq desc";
        List<Resource> list=  sqlManager.execute(sql,Resource.class,Params.ins().add("rid",rid).map());
        return treeList(list,0l);
    }

    @Override
    public Map roleTreeWithIds(Long rid) {
        Query<Resource> query= sqlManager.query(Resource.class);
        List<Resource> list=query.andNotEq("status",-1).select();
        String sql="select DISTINCT(a.id) from bp_resource a join bp_role_resource c on c.resource_id=a.id where role_id=#rid# and (SELECT COUNT(1) from bp_resource b where a.id=b.pid)=0";
        List<Long> ids=  sqlManager.execute(sql,Long.class,Params.ins().add("rid",rid).map());
        List<Map> mapList=treeList(list,0l);
        return new HashMap() {
            {
                put("tree", mapList);
                put("ids", ids);
            }
        };
    }

    @Override
    public List<Map> roleSelect() {
        List<Map> list=sqlManager.execute("select id,name from bp_role where status!=-1",Map.class,null);
        return list;
    }

    public List<Map> treeList(List<Resource> list,Long parentId){
        List mapList = new ArrayList();
        for (Resource resource : list) {
            if (resource.getPid()==parentId) {
                Map map=new HashMap();
                map.put("id",resource.getId());
                map.put("name",resource.getName());
                List<Map> c_node = treeList(list, resource.getId());
                map.put("child", c_node);
                mapList.add(map);
            }
        }
        return mapList;
    };

    @Transactional
    public Long insert(Role role) {
        role.setCreateTime(new Date());
       Long rs= roleDao.insertReturnKey(role).getLong();
        return rs>0?rs:null;
    }

    @Transactional
    public Boolean update(Role role) {
        role.setUpdateTime(new Date());
        Integer rs=roleDao.updateTemplateById(role);
        return rs>0?true:false;
    }

    @Override
    public Boolean del(Role role) {
        return null;
    }

    @Override
    public Role getById(Long id) {
        return null;
    }

    @Override
    public List<Role> getList(Map map) {
        return null;
    }

    @Override
    public void getPageList(PageQuery query) {
        sqlManager.pageQuery("role.pageQuery",Role.class,query);

    }

    @Override
    public Long getCount(Role role) {
        return null;
    }

    @Override
    public Role getBySelf(Role role) {
        return null;
    }

    @Transactional
    public Long saveOrUpdate(Role role) {
        SecurityUser securityUser=SecurityUtil.getSecurityUser();
        if(!StrUtil.isEmptyIfStr(role.getId())){
            role.setUpdateBy(securityUser.getId());
            this.update(role);
            return role.getId();
        }
        else {
            role.setCreateBy(securityUser.getId());
            return this.insert(role);
        }
    }
}
